package com.sike.controller.file;

import jakarta.servlet.http.HttpServletRequest;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestParam;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.time.LocalDate;
import java.time.format.DateTimeFormatter;

/**
 * @author vito
 * @version 1.0
 */
@RestController
public class FilesUploadController {
    @PostMapping("/uploads")
    public String upload(@RequestParam("uploadFiles") MultipartFile[] uploadFiles, HttpServletRequest request) {
        if (uploadFiles == null || uploadFiles.length==0) {
            return "NULL FILE";
        }
        //使用当前日期作为目录名
        LocalDate today =LocalDate.now();
        DateTimeFormatter formatter = DateTimeFormatter.ofPattern("yyyy-MM-dd");
        String todayStr = today.format(formatter);
        //获取上传目标文件夹的绝对路径（也可以是本地路径）
        String realPath = "C:\\edge download\\stringboot\\uploadFiles\\" + todayStr;
        File dateDir = new File(realPath);
        if (!dateDir.isDirectory()) {
            dateDir.mkdirs();
        }
        for(MultipartFile uploadFile:uploadFiles) {
            String filename=uploadFile.getOriginalFilename();
            File target = new File(dateDir,filename);
            try {
                uploadFile.transferTo(target);
                System.out.println(target.getAbsoluteFile());
            }catch (IOException e){
                e.printStackTrace();
            }
        }
        return "SUCCESS";
    }
}
